package xyz.o0o0o.demo.AuthorizationServerDemo3.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

import xyz.o0o0o.demo.AuthorizationServerDemo3.entity.CustomUserDetails;

public class UserServiceImpl implements UserDetailsService {

	private final JdbcTemplate jdbcTemplate;

	public UserServiceImpl(DataSource dataSource) {
		Assert.notNull(dataSource, "DataSource required");
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		String sql = "select * from user_ where username = '" + username + "'";
		CustomUserDetails details = jdbcTemplate.queryForObject(sql, new CustomUserDetailsRowMapper());

//		String sql = "select id,username,password from user_ where username = ?";
//		CustomUserDetails details = jdbcTemplate.queryForObject(sql, new Object[] { username },
//				CustomUserDetails.class);
		return details;
	}

}

class CustomUserDetailsRowMapper implements RowMapper<CustomUserDetails> {

	public CustomUserDetails mapRow(ResultSet rs, int value) throws SQLException {
		CustomUserDetails user = new CustomUserDetails();
		user.setId(new Integer(rs.getInt("id")));
		user.setUsername(rs.getString("username"));
		user.setPassword(rs.getString("password"));
		return user;
	}
}

